<template>
	<view style="background-color: #F2F2F2;">
		<!-- 安全区域顶部适配 -->
		<view class="safe-area-top" v-if="safeArea.top > 20"></view>
		<view>
			<u-row customStyle="margin-bottom: 10rpx;margin-top:40rpx">
				<u-col span="6">
					<!-- 显示当前条数和总条数 -->
					<view class="count-display">
						{{ currentIndex + 1 }} / {{ messages.length }}
					</view>
				</u-col>
				<u-col span="6">
					<view class="fsNum">
						<!-- 识别出来的 单词及 评分 -->
						<!-- {{dataResult}}=== -->
						{{((confidence===0.00||confidence===null)?'':confidence<60&&confidence>0.00)?'分数:'+confidence :'分数:'+confidence }}
					</view>
				</u-col>
			</u-row>
		</view>
		<view class="center-mid">
			<u-row customStyle="margin-bottom: 10rpx">
				<u-col span="12">
					<view class="center-case">
						<view class="left-character-icon"
							@click="playText(messages[currentIndex].character1Audio,messages[currentIndex].character1FyText)">
							<u-icon :name="isPlaying? 'volume-fill' : 'volume'" size="30" color="#ffffff"
								:class="{ 'rotate-animation': isPlaying }"></u-icon>
							<text
								style="padding-left: 30rpx;padding-top: 15rpx;">{{ messages[currentIndex].character1FyText }}</text>
						</view>
					</view>
					<view class="center-case">
						<!-- 中间图片 -->
						<view class="conter-character">
							<image class="conter-image" :src="messages[currentIndex].character1Image" mode="aspectFit">
							</image>
						</view>
					</view>
				</u-col>
			</u-row>
		</view>

		<!-- <view>
			<u-row customStyle="margin-bottom: 10rpx">
				<u-col span="3">
					<view class="left-character">
						<image :src="messages[currentIndex].character1Image" mode="aspectFit"></image>
					</view>
				</u-col>
				<u-col span="6">
					<view class="right-character-icon">
						<text>{{ messages[currentIndex].character2FyText || '点击下方按钮录音' }}</text>
						<u-icon name="mic" :size="isRecording? 35 : 30" :color="isRecording? 'red' : '#ffffff'"></u-icon>
					</view>
				</u-col>
				<u-col span="3">
					<view class="right-character">
						<image :src="messages[currentIndex].character2Image" mode="aspectFit"></image>
					</view>
				</u-col>
			</u-row>
		</view> -->
		<!-- <view>
			<u-row customStyle="margin-bottom: 10rpx">
				<u-col span="6">
					<view class="play-button"
						@click="playText(messages[currentIndex].character1Audio,messages[currentIndex].character1FyText)">
						<image src="https://www.afbeijing.net/static_resources/assets/lb.png" mode="aspectFit"></image>
					</view>
				</u-col>
			</u-row>
		</view> -->
		<view>
			<u-row customStyle="margin-bottom: 10rpx">
				<u-col span="4">
					<view class="prev-button" @click="prevPage" :disabled="currentIndex === 0">
						上一个
					</view>
				</u-col>
				<u-col span="4">
					<view class="record-button" @touchstart="startRecording(messages[currentIndex])"
						@touchend="stopRecording" @touchcancel="stopRecording" :class="{ 'recording': isRecording }">
						<image
							:src="isRecording? 'https://www.afbeijing.net/static_resources/assets/ly.png' : 'https://www.afbeijing.net/static_resources/assets/ly-ing.png'"
							mode="aspectFill"></image>
					</view>
				</u-col>
				<u-col span="4">
					<view class="next-button" @click="nextPage" :disabled="!isRecorded[currentIndex]">
						下一个
					</view>
				</u-col>
			</u-row>
		</view>
		<!-- 安全区域底部适配 -->
		<view class="safe-area-bottom" v-if="safeArea.bottom > 20"></view>
		<!-- 录音遮罩层 -->
		<view v-if="recordingStatus" class="" style="position: absolute;" @click="stopRecording()">
			<view class="recording-status">
				<view v-if="recordingStatus!=='分析中...'">
					{{recordingStatus}}
				</view>
				<view v-if="recordingStatus==='分析中...'" class="recording-status-wz">
					{{recordingStatus}}
				</view>
			</view>
			<view v-if="recordingStatus!=='分析中...'" class="recording-status2">
				点击屏幕取消录音
			</view>
			<view v-if="recordingStatus==='分析中...'" class="recording-status3">
				<image src="https://www.afbeijing.net/static_resources/assets/aijiazai.gif" mode="aspectFill"
					style="height: 170rpx;width: 170rpx;"></image>
			</view>
		</view>
	</view>
</template>

<script>
	import config from "@/src/tools/config.js";
	import {
		sixsSelectGame,
		sixverify,
		sixCompleteGame
	} from "../../api/index";
	// 新引入的插件 开始
	const getToken = require("@/src/utils/token").getToken;
	const SpeechTranscription = require("@/src/utils/st");
	const sleep = require("@/src/utils/util").sleep;
	import calculateFrenchSimilarity from "@/src/utils/nlp-utils.js";
	// 新引入的插件 结束

	export default {
		data() {
			return {
				isLandscape: false, // 用于判断是否为横屏
				score: 100, // 初始积分
				leftCharacterImage: 'https://www.afbeijing.net/static_resources/assets/xiongmaotou.png', // 左侧人物图片路径
				rightCharacterImage: 'https://www.afbeijing.net/static_resources/assets/xiongmaotou.png', // 右侧人物图片路径
				messages: [{
						left: 'connaître.',
						right: ''
					},
					{
						left: 'beau aujourd hui',
						right: ''
					},
					{
						left: 'mange aujourd hui?',
						right: ''
					}
				],

				totalLoops: 0, // 总条数
				matchFlag: false, // 比对结果标志
				currentIndex: 0,
				rightCharacterMessage: '',
				isRecording: false,
				isProcessing: false, // 处理中状态
				recorderManager: null,
				backgroundAudioManager: null,
				waveHeights: [],
				waveInterval: null,
				clsId: null,
				crsId: null,
				clsCrsId: null,
				isPlaying: false, // 语音播放状态
				isListeningTouchMove: false, // 触摸移动监听标志
				touchMoveHandler: null, // 触摸移动事件处理函数
				isRecorded: [], // 记录每一页是否成功录音
				gameId: null, // 当前游戏ID
				safeArea: {}, // 安全区域信息
				recordingTime: 0, // 录音计时
				recordingTimer: null, // 录音计时器
				showMask: false, // 新增：统一控制遮罩层显示


				// 新· 新增参数=====开始
				akid: 'LTAI5t8wy2ykHQYE1UjvEmT8',
				akkey: '2ZcGnTw40mlXcfS8I3mITsz1o17eLA',
				appkey: 'm0EYYUUMZnTG3RcL',
				token: null,
				stStart: false,
				stResult: "未开始识别",
				results: [], // 所有比对结果
				errorMessage: null,
				dataResult: null,
				confidence: 0.00,
				canGoNext: null,
				recordingStatus: null,
				recordErrorCount: null,
				fyText: []

				// 新增参数=====结束
			};
		},
		onLoad: async function(e) {
			this.clsId = e.clsId;
			this.crsId = e.crsId;
			this.clsCrsId = Number(e.id);

			// 获取设备信息和安全区域
			uni.getSystemInfo({
				success: (res) => {
					// 判断屏幕方向是否为横屏
					this.isLandscape = res.screenWidth > res.screenHeight;

					// 获取安全区域信息（适配iPhone X系列）
					this.safeArea = res.safeArea || {};
				},
				fail: (err) => {
					console.error('获取系统信息失败:', err);
				}
			});

			// 监听屏幕旋转事件
			uni.onWindowResize((res) => {
				this.isLandscape = res.size.windowWidth > res.size.windowHeight;
			});

			this.rightCharacterMessage = this.messages[this.currentIndex].right;
			this.recorderManager = uni.getRecorderManager();


			// 创建音频上下文
			this.backgroundAudioManager = uni.createInnerAudioContext();
			this.backgroundAudioManager.onError((err) => {
				console.error('音频播放出错:', err);
				// uni.showToast({
				// 	title: '音频播放出错，请稍后重试',
				// 	icon: 'none'
				// });
				this.isPlaying = false;
			});

			// 监听音频播放结束事件
			this.backgroundAudioManager.onEnded(() => {
				this.isPlaying = false;
			});

			// 加载游戏数据
			this.selectGameList();

			// 新· =====初始化前端语音识别 开始===== \\
			wx.getRecorderManager().onFrameRecorded((res) => {
				if (res.isLastFrame) {
					console.log("record done")
				}
				if (this.st && this.stStart) {
					console.log("send " + res.frameBuffer.byteLength)
					this.st.sendAudio(res.frameBuffer)
				}
			})
			wx.getRecorderManager().onStart(() => {
				console.log("start recording...")
			})
			wx.getRecorderManager().onStop((res) => {
				console.log("stop recording...")
				if (res.tempFilePath) {
					wx.removeSavedFile({
						filePath: res.tempFilePath
					})
				}
			})
			wx.getRecorderManager().onError((res) => {
				// this.checkRecordPermission(); // 检查录音权限
				console.log("recording failed:" + JSON.stringify(res))
			})

			try {
				this.token = await getToken('LTAI5t8wy2ykHQYE1UjvEmT8',
					'2ZcGnTw40mlXcfS8I3mITsz1o17eLA')
			} catch (e) {
				console.log("error on get token:", JSON.stringify(e))
				return
			}
			const app = getApp();
			// 新引入的插件 开始
			let st = new SpeechTranscription({
				url: app.globalData.URL,
				appkey: 'm0EYYUUMZnTG3RcL',
				token: this.token
			})

			st.on("started", (msg) => {
				console.log("Client recv started")
				this.stResult = msg
			})

			st.on("started", (msg) => {
				console.log("Client recv started")
				this.stResult = msg
			})

			st.on("changed", (msg) => {
				console.log("Client recv changed:", msg)
				this.stResult = msg
			})

			st.on("completed", (msg) => {
				console.log("Client recv completed:", msg)
				this.stResult = msg
			})

			st.on("begin", (msg) => {
				console.log("Client recv sentenceBegin:", msg)
				this.stResult = msg
			})
			// 这里是完成录音后  获取实时语音识别出来的文本句子
			st.on("end", (msg) => {
				console.log("=====1 all Client recv sentenceEnd=====:", msg)
				console.log("=====2 header Client recv sentenceEnd=====:", JSON.parse(msg).header)
				console.log("=====3 payload Client recv sentenceEnd=====:", JSON.parse(msg).payload)
				this.stResult = msg
				this.dataResult = JSON.parse(msg).payload.result
				// this.calculateSimilarity(JSON.parse(msg).payload.result, this.fyText)
				// this.confidence = JSON.parse(msg).payload.confidence
			})

			st.on("closed", () => {
				console.log("***********Client recv closed***********")
			})

			st.on("failed", (msg) => {
				console.log("Client recv failed:", msg)
				this.stResult = msg
			})

			this.st = st
			// 新· =====初始化前端语音识别 结束===== \\
		},
		onUnload() {
			// 组件销毁时清理资源
			this.stopRecording(); // 确保录音停止
			this.stopRecordingTimer();
			this.backgroundAudioManager.stop();
			this.backgroundAudioManager.destroy();
			uni.offWindowResize();
		},
		methods: {
			// 新· 新增的开始录音 按钮事件
			onStStart: async function() {
				this.isPlaying = false;
				this.backgroundAudioManager.stop()
				if (!this.st) {
					console.log("st is null")
					return
				}
				if (this.stStart) {
					console.log("st is started!")
					return
				}
				// 防止重复调用
				if (this.isRecording) return;

				let st = this.st
				// 配置参数
				let params = st.defaultStartParams();
				params.max_sentence_silence = 2000;
				params.enable_inverse_text_normalization = false;
				try {
					await st.start(params, true, 6000)
					this.stStart = true
					this.isRecording = true;
					this.recordingStatus = '录音中...';
					this.recordErrorCount = 0; // 重置错误计数
					// 标记不是首次录音
					if (this.isFirstTimeRecord) {
						this.isFirstTimeRecord = false;
					}

					// 设置录音时长计时器
					let seconds = 0;
					this.recordingTimer = setInterval(() => {
						seconds++;
						if (seconds >= 30) { // 30秒自动停止
							this.stopRecording();
						} else {
							this.recordingStatus = `录音中...${seconds}s`;
						}
					}, 1000);
				} catch (e) {
					console.log("start failed:" + e)
					this.isRecording = false;
					return
				}
				wx.getRecorderManager().start({
					duration: 600000,
					numberOfChannels: 1,
					sampleRate: 16000,
					format: "PCM",
					frameSize: 4
				})
			},
			// 新· 新增的结束录音 按钮事件
			onStStop: async function() {
				// 防止重复调用
				if (!this.isRecording) return;

				wx.getRecorderManager().stop()
				await sleep(500)
				if (this.stStart && this.st) {
					try {
						console.log("prepare close st")
						await this.st.close()
						this.stStart = false
						this.isRecording = false
						this.recordingStatus = '';
						this.isPlaying = true;
						// 清除计时器
						if (this.recordingTimer) {
							clearInterval(this.recordingTimer);
							this.recordingTimer = null;
						}
						this.calculateSimilarity(this.dataResult, this.fyText)
					} catch (e) {
						this.confidence = 0.00
						console.log("close st failed:" + e)
					}
				}
			},
			// 新· 计算与所有参考句子的相似度
			calculateSimilarity(e, fyText) {
				console.log('计算与所有参考句子的相似度:', fyText)
				this.confidence = 0.00
				this.errorMessage = '';
				this.results = [];
				var resultsList = []
				try {
					fyText.forEach(reference => {
						console.log(JSON.stringify(reference), '----------------')
						const comparer = new calculateFrenchSimilarity();
						const score = comparer.compare(reference, e);
						let referenceTest = reference
						resultsList.push({
							referenceTest,
							score
						});
					});
					this.confidence = Math.max(...resultsList.map(r => r.score)).toFixed(2) || 0;

					console.log('====新对比函数评分====', this.confidence)
					// 找出最高相似度
					this.canGoNext = true;
					if (this.confidence <= 0.00) {
						this.showResultToast('请重新录音', 'error');
						// this.fyText = null
					} else { 
						this.saveGameResult();
						this.isRecorded[this.currentIndex] = true;
					}
					// if (this.confidence <= 0) {
					// 	this.canGoNext = false;
					// 	this.showResultToast('请重新录音', 'error');
					// 	console.log('=======1=======')
					// } else if (this.confidence < 50) {
					// 	console.log(this.confidence)
					// 	this.showResultToast("再试一下吧", 'warning');
					// 	// 保存游戏结果
					// 	this.saveGameResult();
					// 	this.isRecorded[this.currentIndex] = true;
					// 	console.log('=======2=======')
					// } else if (this.confidence < 70) {
					// 	console.log(this.confidence)
					// 	// 保存游戏结果
					// 	this.saveGameResult();
					// 	this.showResultToast("还行吧", 'success');
					// 	this.isRecorded[this.currentIndex] = true;
					// 	console.log('=======3=======')
					// } else if (this.confidence < 90) {
					// 	// 保存游戏结果
					// 	this.saveGameResult();
					// 	this.showResultToast("还不错", 'success');
					// 	this.isRecorded[this.currentIndex] = true;
					// 	console.log('=======4=======')
					// } else if (this.confidence <= 100 || this.confidence > 100) {
					// 	// 保存游戏结果
					// 	this.saveGameResult();
					// 	this.showResultToast("非常棒", 'success');
					// 	this.isRecorded[this.currentIndex] = true;
					// 	console.log('=======5=======')
					// }
				} catch (error) {
					this.confidence = 0.00
					console.error('相似度计算出错:', error);
					this.errorMessage = '计算相似度时出错，请检查输入';
				}
			},
			// 显示结果提示
			showResultToast(title, icon) {
				uni.showToast({
					title: title,
					icon: icon,
					duration: 2000
				});
			},
			// 新***************end
			// 查询游戏数据
			selectGameList() {
				var jsonData = {
					clsCrsId: this.clsCrsId,
					crsId: this.crsId,
					pageNum: 1,
				};
				sixsSelectGame(jsonData).then(response => {
					console.log('游戏数据加载成功:', response);
					if (response.code === 0 && response.data && response.data.length > 0) {
						this.messages = response.data;
						this.totalLoops = this.messages.length;
						this.isRecorded = new Array(this.messages.length).fill(false); // 初始化录音状态

						// 确保数据中有必要的字段
						this.messages.forEach(item => {
							item.character1FyText = item.character1FyText || '';
							item.character2FyText = item.character2FyText || '';
							item.character1Audio = item.character1Audio || '';
							item.character1Image = item.character1Image || this.leftCharacterImage;
							item.character2Image = item.character2Image || this.rightCharacterImage;
						});
					} else {
						uni.showToast({
							title: '加载游戏数据失败',
							icon: 'none'
						});
					}
				}).catch(error => {
					console.error('加载游戏数据出错:', error);
					uni.showToast({
						title: '网络请求失败，请稍后重试',
						icon: 'none'
					});
				});
			},

			// 开始录音
			startRecording(e) {
				console.log('开始录音:', e);
				this.gameId = e.gameId;
				console.log('开始/停止录音:', e.answerTextList)
				this.fyText = e.answerTextList;
				// 检查是否有音频URL
				if (!e.character1Audio) {
					uni.showToast({
						title: '音频资源不存在',
						icon: 'none'
					});
					return;
				}

				// 检查并请求录音权限
				this.checkAndRequestPermission()
					.then(() => {
						// 显示遮罩层
						// this.showMask = true;
						// this.isRecording = true;
						this.recordingTime = 0;
						this.startRecordingTimer(); //录音倒计时
						// this.recorderManager.start(options);
						this.onStStart() //去录音
					})
					.catch(err => {
						console.error('录音权限处理失败:', err);
						uni.showModal({
							title: '权限提示',
							content: '请在设置中开启录音权限',
							showCancel: false,
							success: (res) => {
								if (res.confirm) {
									// 用户点击确定，尝试打开设置页面
									this.openAppSettings();
								}
							}
						});
					});
			},

			// 检查并请求录音权限
			checkAndRequestPermission() {
				return new Promise((resolve, reject) => {
					// 先检查是否已有录音权限
					uni.getSetting({
						success: (res) => {
							if (res.authSetting['scope.record']) {
								// 已有权限，直接返回
								resolve();
							} else {
								// 没有权限，请求权限
								uni.authorize({
									scope: 'scope.record',
									success: () => {
										resolve();
									},
									fail: (err) => {
										// 用户拒绝了权限请求
										console.error('用户拒绝了录音权限:', err);

										// 提示用户需要权限
										uni.showModal({
											title: '权限需要',
											content: '录音功能需要麦克风权限才能使用',
											confirmText: '去授权',
											cancelText: '取消',
											success: (modalRes) => {
												if (modalRes.confirm) {
													// 用户点击"去授权"，打开设置页面
													this.openAppSettings()
														.then(() => {
															// 从设置页面返回后，再次检查权限
															this.checkPermissionStatus()
																.then(
																	hasPermission => {
																		if (
																			hasPermission
																		) {
																			resolve
																				();
																		} else {
																			reject
																				(new Error(
																					'用户未授予录音权限'
																				));
																		}
																	});
														});
												} else {
													reject(new Error(
														'用户取消了权限请求'));
												}
											}
										});
									}
								});
							}
						},
						fail: (err) => {
							console.error('获取设置失败:', err);
							reject(err);
						}
					});
				});
			},

			// 打开应用设置页面
			openAppSettings() {
				return new Promise((resolve, reject) => {
					uni.openSetting({
						success: (res) => {
							console.log('打开设置成功:', res);
							resolve(res);
						},
						fail: (err) => {
							console.error('打开设置失败:', err);
							reject(err);
						}
					});
				});
			},

			// 检查权限状态
			checkPermissionStatus() {
				return new Promise((resolve, reject) => {
					uni.getSetting({
						success: (res) => {
							resolve(res.authSetting['scope.record'] || false);
						},
						fail: (err) => {
							console.error('获取设置失败:', err);
							reject(err);
						}
					});
				});
			},

			// 停止录音
			stopRecording() {
				// 添加日志和状态检查，防止重复调用
				if (!this.isRecording) {
					// console.log('停止录音: 录音未启动，无需操作');
					return;
				}

				console.log('停止录音');

				// 确保只调用一次onStStop
				if (this.isRecording) {
					this.onStStop();
					this.isRecording = false;
					this.stopRecordingTimer();
				}
			},

			// 开始录音计时器
			startRecordingTimer() {
				this.stopRecordingTimer();
				this.recordingTimer = setInterval(() => {
					this.recordingTime++;
					// 限制最大录音时间
					if (this.recordingTime >= 30) {
						this.stopRecording();
					}
				}, 1000);
			},

			// 停止录音计时器
			stopRecordingTimer() {
				if (this.recordingTimer) {
					clearInterval(this.recordingTimer);
					this.recordingTimer = null;
				}
			},

			// 上一页
			prevPage() {
				if (this.currentIndex > 0) {
					this.currentIndex--;
					this.rightCharacterMessage = this.messages[this.currentIndex].right;
					this.confidence = 0.00; // 重置分数显示
				}
			},

			// 下一页
			nextPage() {
				console.log('尝试切换到下一页，当前页录音状态:', this.isRecorded[this.currentIndex]);

				if (this.isRecorded[this.currentIndex]) {
					// 停止任何可能正在进行的录音
					this.stopRecording();

					if (this.currentIndex === this.messages.length - 1) {
						// 所有页面完成，跳转到积分页
						uni.redirectTo({
							url: '/src/views/pageStudy/common/huodejifen/index2?showButton=false'
						});
					} else {
						// 切换到下一页
						this.currentIndex++;
						this.confidence = 0; // 重置分数显示
						this.rightCharacterMessage = '';
					}
				} else {
					uni.showToast({
						title: '请先完成当前页录音',
						icon: 'none'
					});
				}
			},

			// 语音转文字
			convertVoiceToText(tempFilePath) {
				// 显示处理中状态（遮罩层已打开，只需更新文字）
				this.isProcessing = true;

				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: config.base_url + 'mp/game/three/audio/upload',
						filePath: tempFilePath,
						name: 'file',
						header: {
							'content-type': 'multipart/form-data'
						},
						success: (uploadRes) => {
							try {
								const datas = JSON.parse(uploadRes.data);
								if (datas.code === 0 && datas.data) {
									const jsonData = {
										gameId: this.gameId,
										path: datas.data
									};

									// 调用语音验证API
									sixverify(jsonData).then(response => {
										console.log('语音验证结果:', response);
										if (response.code === 0 && response.data) {
											// 验证成功
											this.matchFlag = true;
											this.isRecorded[this.currentIndex] = true;
											this.score += 10; // 增加积分

											// 保存结果
											this.saveGameResult();

											resolve(this.messages[this.currentIndex]
												.character2FyText);
										} else {
											// 验证失败
											this.matchFlag = false;
											this.isRecorded[this.currentIndex] = false;

											uni.showToast({
												title: '发音不太准确，再试一次吧',
												icon: 'none'
											});

											// reject(new Error('语音验证失败'));
										}

										// 处理完成后隐藏遮罩层
										this.isProcessing = false;
										this.showMask = false;
									}).catch(error => {
										console.error('语音验证出错:', error);
										// 出错时隐藏遮罩层
										this.isProcessing = false;
										this.showMask = false;
										reject(error);
									});
								} else {
									console.error('上传文件失败:', datas);
									// 失败时隐藏遮罩层
									this.isProcessing = false;
									this.showMask = false;
									reject(new Error('文件上传失败'));
								}
							} catch (error) {
								console.error('解析上传结果出错:', error);
								// 出错时隐藏遮罩层
								this.isProcessing = false;
								this.showMask = false;
								reject(error);
							}
						},
						fail: (err) => {
							console.error('文件上传失败:', err);
							// 失败时隐藏遮罩层
							this.isProcessing = false;
							this.showMask = false;
							reject(err);
						}
					});
				});
			},

			// 播放音频
			playText(audio, text) {
				if (!audio) {
					uni.showToast({
						title: '音频资源不存在',
						icon: 'none'
					});
					return;
				}

				// this.isPlaying = !this.isPlaying;
				this.backgroundAudioManager.src = audio;
				this.backgroundAudioManager.play();
			},

			// 比对文本
			compareText(recognizedText, targetText) {
				console.log('比对文本:', recognizedText, targetText);
				if (recognizedText && targetText && recognizedText.trim() === targetText.trim()) {
					console.log('比对结果：正确');
					this.score += 10;
					this.isRecorded[this.currentIndex] = true;

					// 保存游戏结果
					this.saveGameResult();
				} else {
					console.log('比对结果：错误');
					this.score = Math.max(0, this.score - 5); // 最低0分
					this.isRecorded[this.currentIndex] = false;
				}
			},

			// 保存游戏结果
			saveGameResult() {
				if (this.clsCrsId && this.clsId && this.crsId && this.gameId) {
					const jsonData = {
						"clsCrsId": this.clsCrsId,
						"clsId": this.clsId,
						"crsId": this.crsId,
						"gammeId": this.gameId,
						"matchFlag": this.matchFlag
					};

					sixCompleteGame(jsonData).then(response => {
						console.log('保存游戏结果成功:', response);
					}).catch(error => {
						console.error('保存游戏结果失败:', error);
					});
				}
			},

			// 生成波浪动画高度
			generateWaveHeights() {
				const barCount = 10;
				const heights = [];
				for (let i = 0; i < barCount; i++) {
					heights.push(Math.floor(Math.random() * 30) + 10);
				}
				return heights;
			},
		}
	};
</script>

<style lang="scss" scoped>
	page {
		overflow: hidden;
	}

	.safe-area-top {
		position: absolute;
		top: 0rpx;
		left: 0;
		right: 0;
		height: var(--status-bar-height, 0);
		background-color: #F2F2F2;
		z-index: 10;
	}

	.safe-area-bottom {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		height: constant(safe-area-inset-bottom);
		height: env(safe-area-inset-bottom);
		background-color: #F2F2F2;
		z-index: 10;
	}

	.count-display {
		margin-top: 5rpx;
		margin-left: 10%;
		font-size: 16px;
		z-index: 20;
	}

	.score {
		margin-top: 5rpx;
		z-index: 20;
	}

	.scoreSon {
		padding-left: 10rpx;
		display: flex;
		justify-content: space-around;
		align-items: center;
		height: 28rpx;
		border-radius: 14rpx;
		border: 1px solid #808080;
		font-weight: 400;
		font-size: 12rpx;
		color: #333333;
	}

	.scoreIcon {
		display: flex;
		justify-content: space-around;
		align-items: center;
		width: 55rpx;
		height: 28rpx;
		background: #FF8106;
		border-radius: 14rpx;
		font-weight: 400;
		font-size: 12rpx;
		color: #FFFFFF;
	}

	.center-mid {
		display: flex;
		justify-content: space-around;
		align-items: center;
		// margin-top: -5%;
	}

	.center-case {
		display: flex;
		justify-content: space-around;
		align-items: center;
	}

	.conter-character {
		width: 520rpx;
		height: 529rpx;
		border-radius: 120rpx;
		background: #FFFFFF;
		border-radius: 18rpx;
		border: 0px solid #FFB607;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
	}

	.conter-image {
		width: 520rpx;
		height: 529rpx;
	}

	.left-character {
		float: right;
	}

	.fsNum {
		float: right;
		font-size: 22rpx;
		color: #f9a803;
		margin-top: 5rpx;
		margin-right: 10%;
		z-index: 20;
	}

	.right-character {
		float: left;
		overflow: hidden;
	}

	.left-character,
	.right-character {
		width: 120rpx;
		height: 129rpx;
		border-radius: 120rpx;
		background: #FFFFFF;
		border-radius: 18rpx;
		border: 0px solid #FFB607;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
	}

	.left-character image,
	.right-character image {
		width: 100%;
		height: 100%;
		object-fit: contain;
	}

	.left-character text,
	.right-character text {
		margin: 10px 0;
	}

	.left-character-icon {
		margin-top: 30%;
		display: flex;
		line-height: 1.0;
		width: 520rpx;
		/* height: 47rpx; */
		padding-top: 10rpx;
		padding-bottom: 10rpx;
		margin-bottom: 30rpx;
		padding-left: 30rpx;
		background: #FFB607;
		border-radius: 9rpx 9rpx 9rpx 9rpx;
		font-weight: 400;
		color: #FFFFFF;
		cursor: pointer;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
	}

	.left-character-icon::before {
		content: "";
		width: 0px;
		height: 0px;
		border: 10rpx solid #3754E2;
		border-color: transparent #3754E2 transparent transparent;
		position: absolute;
		/* top: -41rpx; */
		left: -18rpx;
	}

	.right-character-icon {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 166rpx;
		line-height: 1;
		position: absolute;
		right: 210rpx;
		top: 120rpx;
		height: 37rpx;
		padding: 10rpx;
		background: #FFB607;
		border-radius: 9rpx 9rpx 9rpx 9rpx;
		font-weight: 400;
		font-size: 14rpx;
		color: #FFFFFF;
		cursor: pointer;
		transition: all 0.3s ease;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
	}

	.right-character-icon::before {
		content: "";
		width: 0px;
		height: 0px;
		border: 10rpx solid #FFB607;
		border-color: transparent transparent transparent #FFB607;
		position: absolute;
		/* top: -41rpx; */
		right: -18rpx;
	}

	.wave-layer {
		position: absolute;
		right: 250rpx;
		top: 190rpx;
		width: 166rpx;
		height: 17rpx;
		opacity: 0.6;
		display: flex;
		justify-content: space-around;
		align-items: flex-end;
	}

	.wave-bar {
		width: 8px;
		background-color: white;
		animation: waveAnimation 0.8s infinite alternate;
	}

	@keyframes waveAnimation {
		from {
			transform: scaleY(1);
		}

		to {
			transform: scaleY(1.5);
		}
	}

	@keyframes rotate {
		from {
			transform: rotate(0deg);
		}

		to {
			transform: rotate(360deg);
		}
	}

	.play-button,
	.record-button {
		width: 120rpx;
		height: 120rpx;
		overflow: hidden;
		border-radius: 50%;
		box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
		transition: all 0.2s ease;
	}

	.play-button {
		float: left;
		margin-left: 30%;
	}

	.record-button {
		position: absolute;
		bottom: calc(120px + constant(safe-area-inset-bottom));
		bottom: calc(120px + env(safe-area-inset-bottom));
		margin-left: 10%;
		bottom: 13%;
	}

	.record-button.recording {
		transform: scale(1.1);
		box-shadow: 0 0 15px rgba(255, 0, 0, 0.3);
	}

	.play-button image,
	.record-button image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.rotate-animation {
		animation: rotate 1s linear infinite;
	}

	.next-button {
		position: absolute;
		bottom: calc(20px + constant(safe-area-inset-bottom));
		bottom: calc(20px + env(safe-area-inset-bottom));
		right: 20px;
		background-color: #FF8106;
		color: white;
		padding: 10px 20px;
		border-radius: 5px;
		cursor: pointer;
		z-index: 20;
		box-shadow: 0 4px 12px rgba(255, 129, 6, 0.2);
		transition: all 0.2s ease;
	}

	.next-button:active {
		transform: translateY(2px);
		box-shadow: 0 2px 6px rgba(255, 129, 6, 0.2);
	}

	.prev-button {
		position: absolute;
		bottom: calc(20px + constant(safe-area-inset-bottom));
		bottom: calc(20px + env(safe-area-inset-bottom));
		left: 20px;
		background-color: #FF8106;
		color: white;
		padding: 10px 20px;
		border-radius: 5px;
		cursor: pointer;
		opacity: 0.5;
		pointer-events: none;
		z-index: 20;
		box-shadow: 0 4px 12px rgba(255, 129, 6, 0.2);
		transition: all 0.2s ease;
	}

	.prev-button:not([disabled]) {
		opacity: 1;
		pointer-events: auto;
	}

	.prev-button:not([disabled]):active {
		transform: translateY(2px);
		box-shadow: 0 2px 6px rgba(255, 129, 6, 0.2);
	}

	/* 录音遮罩层样式 */
	.recording-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.4);
		z-index: 999;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.recording-indicator {
		text-align: center;
	}

	.recording-text {
		color: #f9a803 !important;
		font-size: 24rpx;
		margin-bottom: 10rpx;
	}

	.recording-timer {
		color: white;
		font-size: 36rpx;
		font-weight: bold;
	}

	/* iPhone 14系列适配 */
	@media only screen and (device-width: 390px) and (device-height: 844px) and (-webkit-device-pixel-ratio: 3) {

		/* 针对iPhone 14的特定样式 */
		.left-character-icon {
			left: 230rpx;
		}

		.right-character-icon {
			right: 230rpx;
		}

		.wave-layer {
			right: 230rpx;
		}
	}

	/* iPhone 14 Plus适配 */
	@media only screen and (device-width: 428px) and (device-height: 926px) and (-webkit-device-pixel-ratio: 3) {

		/* 针对iPhone 14 Plus的特定样式 */
		.left-character-icon {
			left: 250rpx;
		}

		.right-character-icon {
			right: 250rpx;
		}

		.wave-layer {
			right: 250rpx;
		}
	}

	/* iPhone 14 Pro适配 */
	@media only screen and (device-width: 393px) and (device-height: 852px) and (-webkit-device-pixel-ratio: 3) {

		/* 针对iPhone 14 Pro的特定样式 */
		.left-character-icon {
			left: 235rpx;
		}

		.right-character-icon {
			right: 235rpx;
		}

		.wave-layer {
			right: 235rpx;
		}
	}

	.recording-status {
		width: 100%;
		height: 105vh;
		position: fixed;
		background-color: rgba(0, 0, 0, 0.6);
		/* opacity: 0.3; */
		z-index: 99999;
		left: 0;
		right: 0;
		top: -15px;
		font-size: 24rpx;
		text-align: center;
		justify-content: center;
		align-items: center;
		display: flex;
		color: #f9a803 !important;

	}

	.recording-status-wz {
		margin-top: -80rpx;
		font-size: 24rpx;
		text-align: center;
		justify-content: center;
		align-items: center;
		color: #f9a803 !important;
	}

	.recording-status2 {
		width: 100%;
		height: 105vh;
		position: fixed;
		z-index: 99999;
		left: 0;
		right: 0;
		top: 25px;
		font-size: 18rpx;
		text-align: center;
		justify-content: center;
		align-items: center;
		display: flex;
		color: #ffffff !important;
	}

	.recording-status3 {
		position: fixed;
		z-index: 99999;
		left: 0;
		right: 0;
		top: 110rpx;
		text-align: center;
		justify-content: center;
		align-items: center;
		display: flex;
	}

	/* iPhone 14 Pro Max适配 */
	@media only screen and (device-width: 430px) and (device-height: 932px) and (-webkit-device-pixel-ratio: 3) {

		/* 针对iPhone 14 Pro Max的特定样式 */
		.left-character-icon {
			left: 255rpx;
		}

		.right-character-icon {
			right: 255rpx;
		}

		.wave-layer {
			right: 255rpx;
		}
	}
</style>